* Kristoffer Balle Hvidberg
* Field of Study and Financial Problems: How Economics Reduces the Risk of Default

********************************************************************************

clear all
set more off

global data "K:\Workdata\704365\kbh\FSFP_Replication_Package\data"
global temp "K:\Workdata\704365\kbh\FSFP_Replication_Package\data\temp"
global raw  "K:\Workdata\704365\kbh\FSFP_Replication_Package\data\raw"

********************************************************************************

import sas "$raw/bef_ind_new.sas7bdat", clear // Retrieved 2020-02-27

drop if mi(pnr)

gen cohort = year(FOED_DAG) 

bysort pnr: egen cohort_temp = max(cohort)
drop cohort
rename cohort_temp cohort
drop if mi(cohort)

drop if mi(PERINDKIALT_13)

gen year = indupd01sourceyear

drop FOED_DAG befupdSourceYear indupd01sourceyear

gen age = year - cohort

save "$temp\bef_ind_new" 

drop if age<27
drop if year<2003
keep if inrange(cohort,1963,1989)

egen grp = group(cohort year)

gen inc_rank = .

sort grp PERINDKIALT_13

levelsof grp, loc(g)
foreach x in `g' {
	di `x'
	xtile inc_rank_temp = PERINDKIALT_13 if grp==`x', n(100)
	replace inc_rank = inc_rank_temp if mi(inc_rank)
	drop inc_rank_temp
}

sort cohort year PERINDKIALT_13
keep pnr year inc_rank
duplicates drop
duplicates tag pnr year, gen(dup)
drop if dup>0
drop dup

save "$temp/inc_rank"


********************************************************************************

use "$temp\bef_ind_new", clear

keep if age==35 | age==40 | age==45

egen grp = group(cohort year)

gen inc_rank_35 = .
gen inc_rank_40 = .
gen inc_rank_45 = .

sort grp PERINDKIALT_13

levelsof grp, loc(g)
foreach x in `g' {
	di `x'
	xtile inc_rank_temp = PERINDKIALT_13 if grp==`x', n(100)
	replace inc_rank_35 = inc_rank_temp if mi(inc_rank_35) & age==35
	replace inc_rank_40 = inc_rank_temp if mi(inc_rank_40) & age==40
	replace inc_rank_45 = inc_rank_temp if mi(inc_rank_45) & age==45
	drop inc_rank_temp
}

keep pnr inc*
sort pnr
duplicates drop

collapse (firstnm) inc_rank_35 (firstnm) inc_rank_40 (firstnm) inc_rank_45, by(pnr)

duplicates report pnr

save "$temp/inc_rank_age"



